from PIL import Image
import PIL
import os
import numpy as np
import scipy

class ImageQueryError(BaseException):
    pass

class ImageQueryShapeNotMatchError(ImageQueryError):
    def __init__(self,shape1,shape2):
        self.shape1=shape1
        self.shape2=shape2
    def __str__(self):
        return f"shape of img1:{self.shape1} != shape of img2:{self.shape2}"

class ImageQuery:
    def __init__(self):
        pass
    def _create_and_image(self,imagepath,imagename):
        try:
            im = Image.open(os.path.join(imagepath, imagename))
        except FileNotFoundError:
            print("filepath:"+imagepath+imagename)
            print("Error:FileNotFoundError")
        except PIL.UnidentifiedImageError:
            print("filepath:"+imagepath+imagename)
            print("Error:PIL.UnidentifiedImageError")
        else:
            #print("No error")
            return im
        #finally:
            #print("in finally")    
            
    def pixel_difference(self,img1_path,img1_name,img2_path,img2_name):
        img1 = self._create_and_image(img1_path,img1_name)
        img2 = self._create_and_image(img2_path,img2_name)
        shape1=img1.size
        shape2=img2.size
        if shape1!=shape2:
            raise ImageQueryShapeNotMatchError(shape1,shape2)
        img1ar=np.array(img1)
        img2ar=np.array(img2)
        pixel_diff=np.abs(img1ar-img2ar)
        return np.sum(pixel_diff)/(img1.width*img1.height)
    
    def histogram_similarity(self,img1_path,img1_name,img2_path,img2_name):
        img1 = self._create_and_image(img1_path,img1_name)
        img2 = self._create_and_image(img2_path,img2_name)
        hist_1 = img1.histogram()
        hist_2 = img2.histogram()
        p_cor = scipy.stats.pearsonr(hist_1, hist_2)[0]
        s_cor = scipy.stats.spearmanr(hist_1, hist_2)[0]
        k_cor = scipy.stats.kendalltau(hist_1, hist_2)[0]
        return p_cor,s_cor,k_cor
    
print(ImageQuery().histogram_similarity(r"C:\Users\User\Desktop\code\pycode\lab7", "zj1.jpg",
                                        r"C:\Users\User\Desktop\code\pycode\lab7","zj2.jpg"))
